package com.bonc.common.utils;

import com.jcraft.jsch.*;

import java.lang.reflect.Field;
import java.util.Properties;

public class SftpUtils {

    public static Session getSftpSession(String sftpHost, Integer sftpPort, String sftpUsername, String sftpPassword){
        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession(sftpUsername, sftpHost, sftpPort);
            session.setPassword(sftpPassword);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
        } catch (JSchException e) {
            e.printStackTrace();
        }
        return session;
    }

    public static ChannelSftp getChannelSftp(Session session) {
        ChannelSftp sftp = null;
        try {
            ChannelSftp channel = (ChannelSftp)session.openChannel("sftp");
            channel.connect();
            Class cl = ChannelSftp.class;
            Field f = cl.getDeclaredField("server_version");
            f.setAccessible(true);
            f.set(channel, 2);
            channel.setFilenameEncoding("utf-8");
            sftp = channel;
        } catch (JSchException e) {
            System.out.println("连接失败");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return sftp;
    }

}
